<?php

// +----------------------------------------------------------------------
// | 用户管理
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 微尘 <yicmf@qq.com>
// +----------------------------------------------------------------------

namespace app\controller\pos\admin;

use app\controller\admin\Common;
use app\model\im\ChatContent as ChatContentModel;
use app\model\pos\Pos as PosModel;
use app\model\pos\PosLevel;
use app\model\ucenter\User as UserModel;
use app\event\ucenter\User as UserEvent;
use app\model\ucenter\AuthGroup as AuthGroupModel;
use app\model\ucenter\UserTag as UserTagModel;
use app\model\ucenter\Tag as TagModel;
use yicmf\builder\Edit;
use yicmf\builder\Table;

class User extends Common
{
    protected function initialize()
    {
        parent::initialize();
    }

    public function _filter()
    {
        $map[] = ['status', '>', -2];
        return $map;
    }

    public function index()
    {

        $where = $this->_filter();
        $statusOptions = [
            [
                'id' => 1,
                'value' => '待回复'
            ],
            [
                'id' => 2,
                'value' => '已回复'
            ]
        ];
        $cateOptions = [
            [
                'id' => 1,
                'title' => '待回复',
                'children' => [[
                    'id' => 1,
                    'title' => '待回复'
                ]]
            ],
            [
                'id' => 2,
                'title' => '已回复'
            ]
        ];
        $tags = TagModel::where('status', 1)->where('store_id', $this->user['store_id'])->select();

        $builder = new Table();
        $builder->model(UserModel::class)
            ->where($where)
//				->excel()
//				->excel(function ($data)
//				{
//					dump($data);
//				})
            ->order('id DESC')
            ->tag($tags)
            //                ->suggest('管理用户信息')
            ->searchTextLike('nickname', '用户昵称')
//                ->searchTabs('keyword', $statusOptions)
            ->keyId()
//				->keyText('email', '邮箱')
//				->keyText('mobile', '手机')
            ->keyText('nickname', '用户昵称')
            ->keyClosure('客户标签', function ($data) {
                $tags = $data->tags()->column('title');
                $html = '';
                foreach ($tags as $tag) {
                    $html .= '<span class="layui-badge layui-bg-green" style="    margin-right: 5px;">' . $tag . '</span>';
                }
                return $html;
//                    return empty($tags)?'':implode('|',$tags);
//                    return AuthGroupModel::where('id',$data['auth_limit_group_id'])->where('store_id',$this->store['id'])->value('title')?:'';
            })
            ->keyText('login_count', '登陆次数')
            ->keyText('create_ip', 'ip')
            ->keyTime('create_time', '注册时间')
            ->keyStatus()
            ->actionUpdate()
            ->actionRestore()
            ->actionForbid('forbid?id={$id}', '黑名单')
            ->actionDelete();

        return $builder->fetch('table_tree');
    }


    public function find()
    {

        $where = $this->_filter();
        $statusOptions = [
            [
                'id' => 1,
                'value' => '是'
            ],
            [
                'id' => 0,
                'value' => '否'
            ]
        ];
        $cateOptions = [
            [
                'id' => 1,
                'title' => '待回复',
                'children' => [[
                    'id' => 1,
                    'title' => '待回复'
                ]]
            ],
            [
                'id' => 2,
                'title' => '已回复'
            ]
        ];
//        $tags = TagModel::where('status', 1)->where('store_id', $this->user['store_id'])->select();

        $ids = $this->request->param('__id');

        $count = PosModel::where('id','in',$ids)->whereNull('user_id')->where('status',1)->count();
        $ids =  PosModel::where('id','in',$ids)->whereNull('user_id')->where('status',1)->column('id');
        $message = '确认划转'.$count.'台POS机？';
        $builder = new Table();
        $builder->model(UserModel::class)
            ->where($where)
//				->excel()
//				->excel(function ($data)
//				{
//					dump($data);
//				})
            ->order('id DESC')
//            ->tag($tags)
            //                ->suggest('管理用户信息')
            ->searchTextLike('nickname', '用户昵称')
            ->searchDateTimeRange('create_time','注册时间')
            ->searchBool('is_effective','有效会员')
            ->searchBool('is_agency','代理')
//            ->searchSelect('is_agency','有效会员',$statusOptions)
//                ->searchTabs('keyword', $statusOptions)
            ->keyId()
//				->keyText('email', '邮箱')
//				->keyText('mobile', '手机')
            ->keyText('nickname', '用户昵称')
            ->keyText('mobile', '手机号')
//            ->keyClosure('客户标签', function ($data) {
//                $tags = $data->tags()->column('title');
//                $html = '';
//                foreach ($tags as $tag) {
//                    $html .= '<span class="layui-badge layui-bg-green" style="    margin-right: 5px;">' . $tag . '</span>';
//                }
//                return $html;
////                    return empty($tags)?'':implode('|',$tags);
////                    return AuthGroupModel::where('id',$data['auth_limit_group_id'])->where('store_id',$this->store['id'])->value('title')?:'';
//            })
            ->keyText('login_count', '登陆次数')
            ->keyBool('is_effective','有效会员')
            ->keyBool('is_agency','代理')
//            ->keyText('create_ip', 'ip')
            ->keyTime('create_time', '注册时间')
//            ->keyStatus()
            ->actionUpdate('pos?user_id={$id}&_pos_ids='.implode(',',$ids), '下发',[0,1], true);

        return $builder->fetch('table_tree');
    }


    public function pos()
    {

        if ($this->request->isPost()) {
            $event = new \app\event\pos\PosTransfer();
            $data = $event->adminGift($this->request->param(),$this->user);
            if (0 === $data['code']) {
                $this->_returnSuccess($data['message']);
            } else {
                $this->_returnError($data['message'], false);
            }
        } else {
            $data['pos_ids'] = $this->request->param('_pos_ids');
            $data['user_id'] = $this->request->param('user_id');
            $data['level'] = 0;
            $data['nickname'] = UserModel::where('id', $data['user_id'])->value('nickname');
            $level = PosLevel::where('status',1)->column('title','id');
            // 同步节点与菜单
            $level = array_merge([0=>'自动配送'],$level);
            $builder = new Edit();
            $builder->title('下发配置');
            $builder
                ->keyHidden('user_id')
                ->keyHidden('pos_ids')
                ->keyLabel('nickname', '合伙人昵称')
                ->keyRadio('level','划拨等级',$level)
                ->data($data);
            $builder->buttonSubmit();
            return $builder->fetch();
        }

    }

    public function service()
    {
        $map[] = ['status', '>', -2];
        $map[] = ['store_id', '=', $this->store['id']];
        $map[] = ['type', '=', 1];

        $group = AuthGroupModel::where('store_id', $this->store['id'])->where('type',2)->where('status', 1)->select();
        $builder = new Table();
        $builder->model(UserModel::class)
            ->where($map)
            ->order('id DESC')
            ->tag($group,'分组','','auth_manage_group_id')
            //                ->suggest('管理用户信息')
            ->searchTextLike('nickname', '用户昵称')
            ->searchText('mobile', '手机号')
            ->buttonUpdate()
            ->keyId()
            ->keyClosure('客服分组', function ($data) {
                return AuthGroupModel::where('id', $data['auth_manage_group_id'])->where('store_id', $this->store['id'])->value('title') ?: '';
            })
            ->keyText('nickname', '客服昵称')
            ->keyText('login_count', '登陆次数')
            ->keyClosure('回复次数', function ($data) {
                return ChatContentModel::where('user_id', $data['id'])->count();
            })
//				->keyText('agent', 'os')
//				->keyText('create_ip', 'ip')
//				->keyTime('create_time', '注册时间')
            ->keyStatus()
            ->actionUpdate()
            ->actionRestore()
            ->actionForbid('forbid?id={$id}', '黑名单')//				->actionDelete()
        ;
        return $builder->fetch();
    }


    public function update()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
//				if (!$param['id']) {
//					$param['password_confirm'] = $param['password'];
//					$result = $this->validate($param, 'User.register');
//				} else {
//					$result = $this->validate($param, 'User.update');
//				}
//				if ($result !== true) {
//					$this->_returnError('用户数据验证失败：' . $result);
//				}
            $event = new UserEvent();
            $result = $event->updateByAdmin($param, $this->user);
            if (0 == $result['code']) {
                $this->_returnSuccess($result['message']);
            } else {
                $this->_returnError($result['message']);
            }
        } else {
            $id = $this->request->get('id', 0);
            if ($id) {
                $data = UserModel::where('id', $id)->find();
                if (!$data) {
                    $this->_returnError('用户信息不存在');
                }
            } else {
                // 新增
                $data = [];
                $data['type'] = 0;
                $data['store_id'] = $this->store['id'];
            }

            $builder = new Edit();
            $builder->title('客服详情');
            $builder->keyHidden('store_id')->keyHidden('type')
                ->keyTextInline('nickname', '昵称', '可重复')
                ->keyImageModel('avatar_id', '头像')
                ->keyTextInline('email', '邮箱')
                ->keyMobile('mobile', '手机');
            if ($data['type'] == 99) {
                $grade = \app\model\ucenter\AuthGroup::where('status', 1)
                    ->where('store_id', $this->store['id'])
                    ->where('type', 0)
                    ->column('title', 'id');
                $builder->keyRadio('auth_limit_group_id', '分组', $grade);
            } else {
                // 客服
                $grade = \app\model\ucenter\AuthGroup::where('status', 1)
                    ->where('store_id', $this->store['id'])
                    ->where('type', 2)
                    ->column('title', 'id');
                $builder->keyRadio('auth_manage_group_id', '分组', $grade)
                    ->keyPassword('password', '新密码', '不填写不修改，默认123123', '123123');
            }

            $builder
//                    ->keySex()
//					->keyDate('birthday', '生日')
//                    ->keyTextInline('qq', 'QQ')
//                    ->keyTextInline('wechat', '微信')
                ->data($data);
            $builder->buttonSubmit();
            return $builder->fetch();
        }
    }

    public function forbid()
    {
        $course = UserModel::where('id', $this->request->param('id'))->find();
        if ($course) {
            $course['status'] = -1;
            if ($course->save()) {
                $this->_returnSuccess('禁用成功');;
            } else {
                $this->_returnError('禁用失败');
            }
        } else {
            $this->_returnError('操作异常');
        }
    }

    public function restore()
    {
        $course = UserModel::where('id', $this->request->param('id'))->find();
        if ($course) {
            $course['status'] = 1;
            if ($course->save()) {
                $this->_returnSuccess('还原成功');;
            } else {
                $this->_returnError('还原失败');
            }
        } else {
            $this->_returnError('操作异常');
        }
    }


    /**
     * 修改资料
     * @return string
     * @throws \Exception
     * @author  : 微尘 <yicmf@qq.com>
     */
    public function profile()
    {
        if ($this->request->isPost()) {
            $result = $this->validate($this->request->post(), 'app\validate\ucenter\User.profile');
            if (true === $result) {
                $user = new UserEvent();
                $data = $user->profile($this->request->param(), $this->user);
                if (0 == $data['code']) {
                    $this->_returnSuccess('资料修改成功！', true);
                } else {
                    $this->_returnError('资料失败，错误信息：' . $data['message']);
                }
            } else {
                $this->_returnError('修改失败，错误信息：' . $result);
            }
        } else {
            $builder = new Edit();
            $builder->title('编辑资料')
//					->keySafeCheck('mobile,email', '安全检测')
                ->keyTextInline('account', '登录名', '不可修改');
//				if (1 == $this->user['is_auth']) {
//					$builder->keyLabel('auth_name', '认证名', '不可修改');
//				}
            $builder->keyTextInline('nickname', '昵称')
                ->keyTextInline('mobile', '手机')
                ->keyEmail('email', '邮箱')
                ->keySex('sex')
                //                    ->keyImageModel('avatar_id', '头像', null, null, 2)
                //                    ->keyTextArea('introduction', '个性签名')
                ->data($this->user)
                ->buttonSubmit('', '保存');
            return $builder->fetch();
        }
    }

}
